<template>
  <van-swipe autoplay="3000" lazy-render>
      <van-swipe-item v-for="image in product.thumbs_text" :key="image">
          <van-image
              width="100%"
              height="20em"
              fit="cover"
              :src="image"
          />
      </van-swipe-item>
  </van-swipe>

  <div class="detailbox">
      <div class="box">
          <div class="left">
              <span>￥</span>{{ product.price }}
          </div>
          <div class="right">
              <div class="sales">{{ product.buy_count }} 人付款</div>
              <div class="region">{{ product.region_text }}</div>
          </div>
      </div>

      <h4>{{ product.name }}</h4>
  </div>

  <div class="allkbox"></div>

  <!-- 商品规格 -->
  <div class="info_choice">
      <!-- Sku 商品规格 -->
      <div class="commodity" @click="SkuShow = true">
          <div class="opt">
              <div class="title wanl-gray">选择</div>
              <div class="option">
                  <div class="selected">
                      <div v-if="Object.getOwnPropertyNames(SelectedProp).length === 0">
                          <span>选择</span>
                          <span v-for="(val,index) in props" :key="index">{{ val }}</span>
                      </div>
                      <div v-else>
                          <span>已选择</span>
                          <span v-for="(val,index) in Object.values(SelectedProp)" :key="index">{{ val }}</span>
                      </div>
                  </div>
              </div>
          </div>
          <div class="wanl-gray">
              <img src="/assets/images/go.png" />
          </div>
      </div>
      <!-- 服务 -->
      <div class="commodity" @click="TipShow = true">
          <div class="opt">
              <div class="title wanl-gray">服务</div>
              <div class="option">
                  <div class="selected">
                      <div>
                          <span>7天无理由退款</span>
                          <span>·</span>
                          <span>24小时内发货</span>
                          <span>·</span>
                          <span>假一赔十</span>
                      </div>
                  </div>
              </div>
          </div>
          <div class="wanl-gray">
              <img src="/assets/images/go.png" />
          </div>
      </div>
  </div>

  <div class="allkbox"></div>

  <!-- 评论 -->
  <div class="comment" @click="ToCommentList">
      <div class="header">
          <div class="title">宝贝评价（{{ CommentCount }}）</div>
          <div class="rate">
              <div class="rate-text">好评率高达{{ ApplauseRate }}%</div>
              <div class="wanl-gray">
                  <img src="/assets/images/go.png" />
              </div>
          </div>
      </div>
      <div class="comment-list">
          <div class="item" v-for="item in CommentList" :key="item.id">
              <div class="user">
                  <div class="avatar">
                      <img :src="item.business.avatar_text" />
                  </div>
                  <div class="nickname">
                      {{item.business.nickname}}
                  </div>
                  <div class="rate">
                      <van-rate 
                          v-model="item.rate"
                          :size="14"
                          color="#ffd21e"
                          void-icon="star"
                          void-color="#eee"
                          readonly
                      />
                  </div>
              </div>
              <div class="content">{{item.comment}}</div>
          </div>
      </div>
  </div>

  <div class="allkbox"></div>

  <!-- 产品详情 -->
  <div class="product-info">
      <div class="title">- - 产品详情 - -</div>

      <div class="content" v-html="product.content"></div>
  </div>

  <!-- 协议条款 -->
  <van-action-sheet v-model:show="TipShow" title="协议条款">
      <div class="ProductTip">
          三、我们如何使用信息 <br />
          四、我们如何共享信息<br />
          五、我们如何转让信息<br />
          六、我们如何公开披露信息<br />
          七、一般储存期限<br />
          八、我们如何确保您的信息安全<br />
          九、您能做什么<br />
          十、我们如何处理未成年人的个人信息<br />
          十一、您的个人信息的存储地点<br />
          十二、本隐私权政策不适用的范围<br />
          十三、本隐私权政策如何更新<br />
          十四、联系我们<br />
      </div>
  </van-action-sheet>

  <!-- SKU -->
  <van-sku
      ref="SkuRef"
      v-model="SkuShow"
      :sku="sku"
      :properties="properties"
      :goods="goods"
      :goods-id="product.id"
      @sku-prop-selected="OnSelectedProp"
      @add-cart="OnAddCart"
      @buy-clicked="OnBuy"
  >
      <template #sku-actions="props">
          <div class="van-sku-actions">
              <van-button square size="large" type="warning" @click="props.skuEventBus.emit('sku:addCart')">加入购物车</van-button>

              <!-- 直接触发 sku 内部事件，通过内部事件执行 onBuyClicked 回调 -->
              <van-button square size="large" type="danger" @click="props.skuEventBus.emit('sku:buy')">立即购买</van-button>
          </div>
      </template>
  </van-sku>

  <div style="height: 50px;"></div>

  <!-- 底部导航栏 -->
  <van-action-bar :placeholder="true">
      <van-action-bar-icon icon="chat-o" text="客服" />
      <van-action-bar-icon icon="cart-o" text="购物车" @click="ToCart" v-if="product.cart_count > 0" :badge="product.cart_count" />
      <van-action-bar-icon icon="cart-o" text="购物车" @click="ToCart" v-else />
      <van-action-bar-icon icon="star" text="已收藏" color="#ff5000" v-if="product.collection_status" @click="OnCollection" />
      <van-action-bar-icon icon="star-o" text="收藏" v-else @click="OnCollection" />
      <van-action-bar-button type="danger" text="立即购买" @click="SkuShow = true" />
  </van-action-bar>
</template>

<script setup>
  /* 
      商品规格组件
      安装指令：npm install vant-sku -S --force
  */
  import VanSku from 'vant-sku';
  import 'vant-sku/dist/index.css';

  const { proxy } = getCurrentInstance()

  let proid = proxy.$route.query.proid ? proxy.$route.query.proid : 0
  let business = proxy.$business ? proxy.$business : {}
  let product = ref({})

  // 评价数据
  const CommentList = ref([]);
  // 好评率
  const ApplauseRate = ref(0);
  // 评价总数
  const CommentCount = ref(0);

  // SKU变量数据
  // 显示商品规格弹出层
  const SkuShow = ref(false);
  // 商品规格数据
  const sku = ref({});
  // 商品属性数据
  const properties = ref([]);
  // sku里的商品信息
  const goods = ref({});
  const SkuRef = ref({});
  // 该商品的规格名称
  const props = ref(['商品规格']);
  // 选中的属性
  const SelectedProp = ref({});

  onBeforeMount(() => GetProductInfo())

  //条款服务
  let TipShow = ref(false)

  //获取商品数据
  const GetProductInfo = async () => {
      let params = { proid } 

      //如果有登录id 那么可以查询一下购物车数量
      if (business.value.id) {
          params.busid = business.value.id
      }

      var result = await proxy.$POST({ url: '/product/info', params })

      if (result.code == 0) {
          proxy.$fail({
              message: result.msg,
              onClose: () => proxy.$router.go(-1)
          })

          return false
      }

      //渲染数据
      product.value = result.data.product
      CommentList.value = result.data.CommentList

      // 把评分转成整数，因为评分组件绑定值的数据类型是Number
      CommentList.value.map((item) => item.rate = parseInt(item.rate))
      ApplauseRate.value = result.data.ApplauseRate;
      CommentCount.value = result.data.CommentCount;

      // sku数据
      sku.value = result.data.sku
      properties.value = Object.values(result.data.properties)
      goods.value = {picture: product.value.thumb_text}
      props.value = result.data.props.length > 0 ? result.data.props : ['数量'];
  }

  //商品收藏
  const OnCollection = async () =>
  {
      //判断是否有登录
      if(!business.value || Object.getOwnPropertyNames(business.value).length <= 0)
      {
          proxy.$confirm({
              title: '登录提醒',
              message: '是否确认跳转到登录？'
          }).then(() => {
              //保留当前页面的地址到cookie中
              proxy.$cookies.set('redirect', {query:{proid},path:'/product/info'})

              proxy.$router.push('/business/login')
          }).catch((err) => {})
          return false
      }

      //有登录
      var params = {
          busid: business.value.id,
          proid
      }

      var result = await proxy.$POST({url: '/product/collection', params})

      if(result.code == 0) return proxy.$fail(result.msg)

      product.value.collection_status = result.data == 'add' ? true : false
  }

  // 跳转到购物车界面
  const ToCart = () => proxy.$router.push('/cart')

  // 跳转评论列表
  const ToCommentList = () => proxy.$router.push({path: '/product/comment', query: {proid}})

  // 切换商品规格
  const OnSelectedProp = ({propValue}) =>
  {
      SelectedProp.value[propValue.skuKeyStr] = propValue.name;
  }

  //添加购物车
  const OnAddCart = async (SkuData) =>
  {
      //判断是否有登录
      if(!business.value || Object.getOwnPropertyNames(business.value).length <= 0)
      {
          proxy.$confirm({
              title: '登录提醒',
              message: '是否确认跳转到登录？'
          }).then(() => {
              //保留当前页面的地址到cookie中
              proxy.$cookies.set('redirect', {query:{proid},path:'/product/info'})

              proxy.$router.push('/business/login')
          }).catch((err) => {})
          return false
      }

      //有登录
      
      // 判断是否有选择规格
      if(properties.value.length > 0 && !SkuData.selectedSkuComb)
      {
          proxy.$fail('请选择商品规格');
          return false;
      }

      // 购买数量
      let SelectedNum = SkuData.selectedNum

      if(SelectedNum <= 0)
      {
          proxy.$fail('购买数量不能小于等于0');
          return false;
      }

      // 选择的属性id
      let relationids = [];

      // 有规格
      if(properties.value.length > 0)
      {
          let SkuProps = SkuData.selectedSkuComb.properties;
          
          for(let item of SkuProps)
          {
              let id = item.v[0] ? item.v[0]['id'] : 0;
              if(id) relationids.push(id);
          }
      }

      //组装数据
      var params = {
          busid: business.value.id,
          proid: proid,
          nums: SelectedNum,
          relationids:relationids.join(','), //规格id
      }

      //发送请求
      var result = await proxy.$POST({url: '/cart/add', params})

      if(result.code == 0)
      {
          proxy.$fail(result.msg)
          return false
      }

      SkuShow.value = false
      
      //更新购物车数量
      product.value.cart_count = result.data;
      
      proxy.$confirm({
          title:'加入购物车成功',
          message:'是否跳转购物车进行结算？'
      }).then(() => proxy.$router.push('/cart')).catch(err => {})
  }

  //立即购买
  const OnBuy = async (SkuData) =>
  {
      //判断是否有登录
      if(!business.value || Object.getOwnPropertyNames(business.value).length <= 0)
      {
          proxy.$confirm({
              title: '登录提醒',
              message: '是否确认跳转到登录？'
          }).then(() => {
              //保留当前页面的地址到cookie中
              proxy.$cookies.set('redirect', {query:{proid},path:'/product/info'})

              proxy.$router.push('/business/login')
          }).catch((err) => {})
          return false
      }

      //有登录
      
      // 判断是否有选择规格
      if(properties.value.length > 0 && !SkuData.selectedSkuComb)
      {
          proxy.$fail('请选择商品规格');
          return false;
      }

      // 购买数量
      let SelectedNum = SkuData.selectedNum

      if(SelectedNum <= 0)
      {
          proxy.$fail('购买数量不能小于等于0');
          return false;
      }

      // 选择的属性
      let relations = [];

      // 商品价格
      let price = product.value.price

      // 转浮点数
      let total = parseFloat(price);

      // 判断商品是否属于直播商品
      let type = product.value.live_price ? 'live' : 'product';

      // 有规格
      if(properties.value.length > 0)
      {
          // 选中的属性
          let SkuProps = SkuData.selectedSkuComb.properties;
          
          for(let item of SkuProps)
          {
              // 获取规格
              let prop = item.v[0] ? item.v[0] : {};

              if(prop.id)
              {
                  // 每个规格的加价
                  let PropPrice = (prop.price / 100).toFixed(2);

                  // 计算出所有选中的规格加价后的商品价格
                  total += parseFloat(PropPrice);

                  relations.push({
                      title:item.k ? item.k : '',
                      value:prop.name,
                      price:PropPrice
                  })
              }
          }
      }

      let data = [];

      // 组装数据
      data.push({
          proid: proid,
          nums: SelectedNum,
          product:product.value,
          total:(total * SelectedNum).toFixed(2),
          price:total.toFixed(2),
          attrs:relations, // 商品规格
          type
      })

      //把数据放到pinia缓存中
      proxy.$cart.value = data

      proxy.$router.push({path: '/cart/confirm'})
  }

</script>

<style scoped>
  @import url('/assets/css/ProductInfo.css');
</style>